package com.kj.xuyuan.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.kj.xuyuan.MainActivity;
import com.kj.xuyuan.R;
import com.kj.xuyuan.base.BaseActivity;
import com.kj.xuyuan.base.BaseModel;
import com.kj.xuyuan.base.Constants;
import com.kj.xuyuan.http.JsonCallback;
import com.kj.xuyuan.http.OkGoUtil;
import com.kj.xuyuan.http.UrlConstants;
import com.kj.xuyuan.model.LoginBean;
import com.kj.xuyuan.util.LogUtils;
import com.kj.xuyuan.util.SPUtils;
import com.kj.xuyuan.util.StringUtils;
import com.kj.xuyuan.util.ToastUtil;
import com.lzy.okgo.model.Response;

import java.util.HashMap;
import java.util.Map;

import androidx.annotation.NonNull;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class VerifyCodeActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_get_code_mobile)
    TextView tvGetCodeMobile;
    @BindView(R.id.tv_pass_word_one)
    TextView tvPassWordOne;
    @BindView(R.id.tv_pass_word_two)
    TextView tvPassWordTwo;
    @BindView(R.id.tv_pass_word_three)
    TextView tvPassWordThree;
    @BindView(R.id.tv_pass_word_four)
    TextView tvPassWordFour;
    @BindView(R.id.ed_password)
    EditText edPassword;
    @BindView(R.id.tv_re_get_code)
    TextView tvReGetCode;
    @BindView(R.id.tv_next)
    TextView tvNext;

    private String code;
    private String mobile;
    private int countDown;

    public static void actionStar(Context context,String mobile) {
        Intent intent = new Intent(context, VerifyCodeActivity.class);
        intent.putExtra("mobile",mobile);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {

    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_verify_code;
    }

    @Override
    protected void initView() {

        mobile = getIntent().getStringExtra("mobile");
        if(StringUtils.isEmpty(mobile)){
            ToastUtil.showDataErrorToast(context);
            finish();
        }

        tvGetCodeMobile.setText("已发送到：+86 "+mobile);
        startCountDown();

        edPassword.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                code = edPassword.getText().toString().trim();
                LogUtils.d(TAG,"code ="+code);
                setCode();
            }
        });
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    if(countDown > 0){
                        countDown --;
                        tvReGetCode.setText("重新获取("+countDown+")");
                        mHandler.sendEmptyMessageDelayed(0,1000);
                    }else{
                        tvReGetCode.setText("重新获取");
                        tvReGetCode.setClickable(true);
                    }
                    break;
            }
        }
    };

    private void startCountDown() {
        countDown = 60;
        tvReGetCode.setText("重新获取("+countDown+")");
        tvReGetCode.setClickable(false);
        mHandler.sendEmptyMessageDelayed(0,1000);
    }

    private void setCode() {
        if(code == null || code.length() == 0){
            tvPassWordOne.setText("");
            tvPassWordTwo.setText("");
            tvPassWordThree.setText("");
            tvPassWordFour.setText("");
            return;
        }
        for(int i = 1;i<=4;i++){
            if(code.length() >= i){
                setCodeText(i,true);
            }else{
                setCodeText(i,false);
            }
        }
    }

    private void setCodeText(int length, boolean input) {
        switch (length){
            case 1:
                if(input){
                    tvPassWordOne.setText("*");
                }else{
                    tvPassWordOne.setText("");
                }
                break;
            case 2:
                if(input){
                    tvPassWordTwo.setText("*");
                }else{
                    tvPassWordTwo.setText("");
                }
                break;
            case 3:
                if(input){
                    tvPassWordThree.setText("*");
                }else{
                    tvPassWordThree.setText("");
                }
                break;
            case 4:
                if(input){
                    tvPassWordFour.setText("*");
                }else{
                    tvPassWordFour.setText("");
                }
                break;
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getTitleBarType() {
        return -1;
    }

    @OnClick({R.id.iv_back, R.id.tv_re_get_code, R.id.tv_next})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_re_get_code:
                getCode();
                break;
            case R.id.tv_next:
                //登录接口  注册过信息到主页，刚注册账号到填写信息页
                if(StringUtils.isEmpty(code) || code.length() < 4){
                    ToastUtil.showToast(context,"验证码未填写");
                }
                login();
                break;
        }
    }

    private void login() {
        Map map = new HashMap();
        map.put("mobile",mobile);
        map.put("type","2");
        map.put("code",code);

        OkGoUtil.postRequest(getContext(), UrlConstants.LOGIN, map, new JsonCallback<BaseModel<LoginBean>>() {
            @Override
            public void onSuccess(Response<BaseModel<LoginBean>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        LoginBean.UserinfoBean bean = response.body().getData().getUserinfo();
                        saveData(bean);
                        if(StringUtils.isEmpty(bean.getYears())){//无年龄,刚注册用户，跳转完善信息页
                            startActivity(EditInfoActivity.class);
                        }else{
                            startActivity(MainActivity.class);
                            SPUtils.setBooleanData(context, Constants.IS_LOGIN,true);
                        }
                        finish();
                    }
                }
            }

            @Override
            public void onError(Response<BaseModel<LoginBean>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
            }
        });
    }

    private void saveData(LoginBean.UserinfoBean bean) {
        SPUtils.setIntData(context, Constants.UID,bean.getId());
        SPUtils.setStringData(context, Constants.TOKEN,bean.getToken());
        SPUtils.setStringData(context, Constants.RONG_TOKEN,bean.getRy_token());
        SPUtils.setStringData(context, Constants.MOBILE,bean.getMobile());
        SPUtils.setStringData(context, Constants.AVATAR,bean.getAvatar());
    }

    private void getCode() {
        Map map = new HashMap();
        map.put("mobile",mobile);
        map.put("event","register");

        OkGoUtil.postRequest(getContext(), UrlConstants.GET_CODE, map, new JsonCallback<BaseModel<?>>() {
            @Override
            public void onSuccess(Response<BaseModel<?>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        startCountDown();
                    }
                    ToastUtil.showToast(context,response.body().getMsg());
                }
            }

            @Override
            public void onError(Response<BaseModel<?>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mHandler != null){
            mHandler.removeMessages(0);
            mHandler = null;
        }
    }
}